package cn.nicholasld.nmqs.message;

import cn.nicholasld.nmqs.config.WebSocketConfig;
import cn.nicholasld.nmqs.message.mqtt.MyMQTT;
import com.alibaba.druid.util.StringUtils;
import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Base64;
import java.util.concurrent.CopyOnWriteArraySet;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author NicholasLD
 * @createTime 2023/3/29 00:33
 */
@ServerEndpoint(value = "/websocket/{token}/{sendTopic}/{receiveTopic}/{qos}", configurator = WebSocketConfig.class)
@Component
public class MyWebSocket {

    //创建一个线程池
    private final ExecutorService executorService = Executors.newVirtualThreadPerTaskExecutor();

    Logger logger = LoggerFactory.getLogger(MyWebSocket.class);



    //静态变量，用来记录当前在线连接数。应该把它设计成线程安全的。
    private static int onlineCount = 0;

    //concurrent包的线程安全Set，用来存放每个客户端对应的MyWebSocket对象。
    private static final CopyOnWriteArraySet<MyWebSocket> webSocketSet =
            new CopyOnWriteArraySet<>();

    //与某个客户端的连接会话，需要通过它来给客户端发送数据
    private Session session;

    private MyMQTT myMQTT;

    //接收token
    private String token;

    private String sendTopic;

    private String receiveTopic;
    private int qos;

    /**
     * 连接建立成功调用的方法
     * @param session session为与某个客户端的连接会话，需要通过它来给客户端发送数据
     * @param token token用于接收url中的参数
     */
    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token, @PathParam("sendTopic") String sendTopic, @PathParam("receiveTopic") String receiveTopic, @PathParam("qos") Integer qos) {
        this.session = session;
        this.token = token;
        //将topic进行base64解码，确保/不会被转义，导致mqtt无法订阅
        this.sendTopic = new String(Base64.getUrlDecoder().decode(sendTopic));
        this.receiveTopic = new String(Base64.getUrlDecoder().decode(receiveTopic));
        //如果qos为空，默认为0
        this.qos = qos;
        //token为null，不允许连接
        if (StringUtils.isEmpty(token)) {
            try {
                logger.error("[Websocket] Websocket连接失败，token为null");
                session.close();
            } catch (IOException e) {
                logger.error("[Websocket] Websocket IO异常",e);
            }
            return;
        }
        webSocketSet.add(this);     //加入set中
        addOnlineCount();           //在线数加1
        logger.info("[Websocket] Websocket有新连接加入，SessionID:"
                + session.getId()
                + "，token为:"
                + token
                + "，当前在线人数为:"
                + getOnlineCount());
        try {
            sendMessage("[Websocket] 连接成功，您的token为：" + token + "，正在连接远程服务器...");

            //异步连接MQTT
            connectMqttAsync();


        } catch (IOException e) {
            logger.error("[Websocket] Websocket IO异常",e);
        }
    }

    public void connectMqttAsync() {
        executorService.execute(() -> {
            myMQTT = new MyMQTT(token, session, sendTopic, receiveTopic, qos);
            myMQTT.connect();
        });
    }

    /**
     * 连接关闭调用的方法
     */
    @OnClose
    public void onClose() {
        //释放线程
        myMQTT.release();
        executorService.shutdown();
        webSocketSet.remove(this);  //从set中删除
        subOnlineCount();           //在线数减1
        logger.info("[Websocket] Websocket有一连接关闭，SessionID:"+ session.getId() +"，当前在线人数为" + getOnlineCount());
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message 客户端发送过来的消息
     * @param session 接收消息的session会话
     */
    @OnMessage
    public void onMessage(String message, Session session) throws MqttException {
        logger.info("[Websocket] 来自客户端 SessionID:"+ session.getId() +" 的消息:" + message);
        //发送到MQTT
        myMQTT.publish(message);
    }

    /**
     * 发生错误时调用
     * @param session session会话
     */
    @OnError
    public void onError(Session session, Throwable error) {
        logger.error("[Websocket] Websocket发生错误",error);
    }


    public void sendMessage(String message) throws IOException {
        this.session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }

    public static void sendMessage(String message, Session session) throws IOException {
        session.getBasicRemote().sendText(message);
        //this.session.getAsyncRemote().sendText(message);
    }


     /**
      * 群发自定义消息
      * */
    public static void sendInfo(String message) throws IOException {
        for (MyWebSocket item : webSocketSet) {
            try {
                item.sendMessage(message);
            } catch (IOException e) {
                continue;
            }
        }
    }

    public static synchronized int getOnlineCount() {
        return onlineCount;
    }

    public static synchronized void addOnlineCount() {
        MyWebSocket.onlineCount++;
    }

    public static synchronized void subOnlineCount() {
        MyWebSocket.onlineCount--;
    }
}
